package com.yy.QSManage.interceptor;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.yy.QSManage.enums.ErrorCodeEnum;
import com.yy.QSManage.exception.ServiceException;
import com.yy.QSManage.service.FaSysMemberService;
import com.yy.QSManage.tool.JwtTool;
import com.yy.QSManage.tool.RedisTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 鉴权拦截器
 */
@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    private final String MEMBER_TOKEN = "member_token:{}";
    private final String TOKEN = "token";
    @Autowired
    RedisTool redisTool;
    @Autowired
    FaSysMemberService memberService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod) || HttpMethod.OPTIONS.matches(request.getMethod().toUpperCase())) {
            return true;
        }
        String token = request.getHeader(TOKEN);
        if(StrUtil.isEmpty(token)){
            throw new ServiceException("token不能为空");
        }
        String userToken = StrUtil.format(MEMBER_TOKEN, DigestUtil.md5Hex(token));
        if(redisTool.hasKey(userToken)){
            // 获取公钥
            String publicKey = redisTool.get(userToken).toString();
            JwtTool.verifyToken(token, publicKey);
            memberService.refresh(token);
        }else{
            throw new ServiceException(ErrorCodeEnum.TOKEN_EXPIRE);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }



}
